//$Id: User.java 2360 2006-10-25 20:17:46Z gavin $
package org.jboss.seam.example.registration;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang.StringUtils;
import org.hibernate.validator.Length;
import org.hibernate.validator.NotNull;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

@Entity
@Name("user")
@Scope(ScopeType.CONVERSATION)
@org.jboss.seam.annotations.Role(name = "current_user",scope = ScopeType.SESSION)
@Table(name = "users")
public class User implements Serializable {
	private static final long serialVersionUID = 1881413500711441951L;

	private long id;
	private String username;
	private String password;
	private String name ;

	/**
	 * roles represent in comma separated string
	 */
	private String roleExpr;

	public User(String name, String password, String username) {
		this.name = name;
		this.password = password;
		this.username = username;
	}

	public User() {
	}

	public void setId(long id) {
		this.id = id;
	}

	@Id @GeneratedValue(strategy = GenerationType.AUTO)
	public long getId() {
		return id;
	}

	@NotNull(message = "[真实姓名] 不能为空")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@NotNull
	@Length(min = 5, max = 15, message = "[密码] 长度必须在5~15之间")
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@NotNull(message = "[用户名] 不能为空")
	@Length(min = 5, max = 15)
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	@Override
	public String toString() {
		return "User(" + username + ")";
	}

	public void setRoles(List<Role> roles) {
		String result = "";
		for (Role role : roles) {
			result += (role.name() + ",");
		}
		setRoleExpr(result.substring(0, result.length() - 1));
	}

	@Transient
	public List<Role> getRoles() {
		List<Role> roles = new ArrayList<Role>();
		if (!StringUtils.isEmpty(getRoleExpr())) {
			for (String role : StringUtils.splitByWholeSeparator(getRoleExpr(),
					",")) {
				roles.add(Role.valueOf(role));
			}
		}
		return roles;
	}

	public void setRoleExpr(String roleExpr) {
		this.roleExpr = roleExpr;
	}

	public String getRoleExpr() {
		if (StringUtils.isEmpty(roleExpr)) {
			roleExpr = Role.USER.name() + "," + Role.GUEST.name();
		}
		return roleExpr;
	}
}
